<?php
App::import('Vendor', 'linkbot');
App::import('Vendor', 'email_message');
App::import('Vendor', 'image');

class Login extends AppModel{
	var $name = 'Login';
	var $useTable           = 'users';
	var $detailsTable       = 'users_information';
	var $gameTable          = 'game_info';
	var $gameLocationsTable = 'game_locations';
	var $uses               = array('Security');
	
	function getGameCities(){
		$result = $this->query("SELECT DISTINCT `city_name` 
			FROM `{$this->gameLocationsTable}`");
		$cities = "";
		foreach($result as $res){
			$cities .= $res[$this->gameLocationsTable]['city_name'].", ";
		} 
		$cities = substr($cities,0,-2);
		return $cities;
	}
	
	function getGroups($group_id=""){
		$games = array();
		$result = $this->query("SELECT g.`game_id`, g.`game_name`, l.`city_name`,
					g.`game_location_id`, (SELECT COUNT(DISTINCT `user_id`) 
											FROM `{$this->gameTable}` 
											WHERE `game_id` = g.`game_id`
											GROUP BY `game_id`) as `users_nr` 
			FROM `{$this->gameTable}` as g,
				`{$this->gameLocationsTable}` as l
			WHERE g.`game_location_id` = l.`game_location_id` ".
			(isset($group_id)&&!empty($group_id)?" AND g.`game_id` = {$group_id} ":"").
			" GROUP BY g.`game_id`".
			(!isset($group_id)||empty($group_id)?" HAVING `users_nr`<20 ":""));
		foreach($result as $res){
			$games[] = array_merge($res['g'],$res['l']);
		}
		if(!empty($group_id)){
			return $games[0];
		}
		return $games;
	}
	
	function checkLogin($params){
		$sess_info = array();
		$query = "SELECT * 
				FROM `{$this->useTable}`
				WHERE `user_email`='".$params['email']."'";
		$result = $this->query($query);
		
		if(count($result)>0){
			foreach($result as $res){
				$password  = $res[$this->useTable]['password'];
				$givenPass = $this->processPassword($params['password']);
				if($password == $givenPass){
					$query = "UPDATE `{$this->useTable}`
						SET `logged` = '1'
						WHERE `user_email` = '".$this->escape($params['email'])."'";
					$result = $this->query($query);
					$query = "SELECT u.*, g.`game_id` 
							FROM `{$this->useTable}` as u,
								`{$this->gameTable}` as g 
							WHERE u.`user_email`='".$this->escape($params['email'])."' 
								AND g.`user_id` = u.`user_id`";
					$result = $this->query($query);
					foreach($result as $res){
						$sess_info = array_merge($res['u'],$res['g']);
					}
				}else{
					$error = 'The password/email address is incorrect!';
				}
			}
		} 
		return $sess_info;
	}
	
	function processPassword($password){
		$salt     = Configure::read('Security.salt');
		$password = $password.$salt;
		return md5($password);		
	}
	
	function signOut($sessionKey){
		$query = "UPDATE `{$this->useTable}`
			SET `logged` = 0
			WHERE `user_id` = '".$sessionKey."'";
		$result = $this->query($query);	
	}
	
	function createAccount($params,$group_id){
		$query = "SELECT * 
				FROM `{$this->useTable}`
				WHERE `user_email`='".$this->escape($params['email'])."'";
		$result = $this->query($query);
		if(count($result)>0){
			return "You already have an account. Please go to 'Recover password' tab.";
		}
		if(isset($params['avatar']) && $params['avatar']['size'] >= 1000000) 
            return 'The image is too big. Please try again with a smaller image.';  
        else {     
        	//insert the data in the DB            
			$givenPass = $this->processPassword($params['password']);
			$query = "INSERT INTO `{$this->useTable}` (`user_email`, `password`)
				VALUES ('".$this->escape($params['email'])."', '".$givenPass."')";
			$result = $this->query($query);
			
			//insert the image in the file if any
            $result = $this->query("SELECT LAST_INSERT_ID() AS `id`");
			foreach($result as $res){
				$nr = $res[0]['id'];
			}			
			
			$query = "INSERT INTO `{$this->detailsTable}` (`user_id`, 
				`last_name`, `first_name`, `sex`)
				VALUES (LAST_INSERT_ID(),'".$this->escape($params['last_name'])."',
					'".$this->escape($params['first_name'])."','".$params['sex']."')";
			$result = $this->query($query);
			
			if(empty($params['avatar']['name']) || empty($params['avatar']['size'])) {
				$urlimg = "img/users/avatar_{$params['sex']}.gif";
			}else {
 				$urlimg = "img/users/".$nr."_avatar.jpg";		
 				try{
 					move_uploaded_file($params['avatar']['tmp_name'] ,'img/users/'.$params['avatar']['name']);
 				}catch(Execption $e){}
 				$img = new Wizart_Image('img/users/'.$params['avatar']['name']);
				$img->cropToSize(50,50)->store($urlimg);	
				if(file_exists('img/users/'.$params['avatar']['name'])) 
					unlink('img/users/'.$params['avatar']['name']);
			}		
			//now insert the image in the DB		
			$query = "UPDATE `{$this->detailsTable}` 
					SET `img_url` = '{$urlimg}'  
					WHERE `user_id`= {$nr}";
			$result = $this->query($query);					
			//fix the groups issue_____________________________________________
			if(!empty($group_id)) {
				$game = $this->getGroups($group_id);
				$this->query("INSERT INTO `{$this->gameTable}`(`game_id`,
					`user_id`,`game_location_id`,`game_name`) 
					VALUES({$game['game_id']},{$nr},{$game['game_location_id']},
						'".$this->escape($game['game_name'])."');");
			}else{
				//select location id_________________________________________
				$result = $this->query("SELECT `game_location_id` 
					FROM `{$this->gameLocationsTable}` 
					WHERE `city_name`='{$params['city_name']}'");
				foreach($result as $res) {
					$location_id = $res[$this->gameLocationsTable]['game_location_id'];
				}
				//get the next game_id ________________________________________
				$result = $this->query("SELECT MAX(`game_id`) as max 
					FROM `{$this->gameTable}`");
				foreach($result as $res) {
					$game_id = $res[0]['max']+1;
				}
				$this->query("INSERT INTO `{$this->gameTable}`(`game_id`,
					`user_id`,`game_location_id`,`game_name`) 
					VALUES({$game_id},{$nr},{$location_id},'".$this->escape($params['game_name'])."');");
			}
		}
		return 0;
	}
	
	function getPassword($params){
		$from_name     = T_SITE_TITLE;
		$from_address  = T_SITE_EMAIL;
		$to_name       = '';
		$to_address    = $params['email'];
		$subject       = T_SITE_TITLE.' | '.'recover password';
		$random_string = '';
		while(strlen($random_string)<2){
			$random_string = substr(md5(uniqid(rand(), true)), 0, 10);
		}
		$new_password = $this->processPassword($random_string);
		$message      = "Email address: {$params['email']}\n". 
				"Password is:{$random_string} \n".
				"\nPlease change the password after you login.";
		//update the password in the DB
		$query = "UPDATE `{$this->useTable}` 
					SET `password` = '{$new_password}'
				WHERE `user_email`= '".$this->escape($params['email'])."'";
		$result = $this->query($query);
		//sent email
		$this->sendTextEmail($from_name,$from_address, $to_name, $to_address, 
				$subject, $message);
	}
	
	function getDetails($id){
		$query = "SELECT a.*, b.`user_email` 
				FROM `{$this->detailsTable}` AS a, `{$this->useTable}` AS b  
				WHERE  b.`user_id`= a.`user_id` AND b.`user_id`= {$id}";
		$result = $this->query($query);
		$details = array();
		foreach($result as $res){
			$details = array_merge($res['a'], $res['b']); 
		}
		return $details;
	}
	
	function changeInfo($id, $params){
		//update the passwors if isset
		if(isset($params['re_password']) && !empty($params['re_password'])) {
			$new_pass = $this->processPassword($params['re_password']);
			$query = "UPDATE `{$this->useTable}` 
						SET `password` = '{$new_pass}'
					WHERE `user_id`= {$id}";
			$result = $this->query($query);
		}	
		//if there is a new avatar upload it
		if(!empty($params['avatar']['name']) && !empty($params['avatar']['size'])) {
			$urlimg = "img/users/".$id."_avatar.jpg";		
			try{
	 			move_uploaded_file($params['avatar']['tmp_name'] ,'img/users/'.$params['avatar']['name']);
	 		}catch(Execption $e){}
	 			$img = new Wizart_Image('img/users/'.$params['avatar']['name']);
				$img->cropToSize(50,50)->store($urlimg);	
				if(file_exists('img/users/'.$params['avatar']['name'])) 
					unlink('img/users/'.$params['avatar']['name']);
		}		
		//update everythins that was changes	
		$query = "UPDATE `{$this->detailsTable}` 
			SET `first_name` = '".$this->escape($params['first_name'])."'
			   ,`last_name` = '".$this->escape($params['last_name'])."'
				".(isset($urlimg)&&!empty($urlimg)?",`img_url`='{$urlimg}'":"")."
			WHERE `user_id`= {$id}";
		$result = $this->query($query);
	}
}